package com.huxiu.yd.fragments;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.R;
import com.huxiu.yd.SearchActivity;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.DiscoveryViewHolder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by kHRYSTAL on 15/9/18:上午11:37.
 */
public class DiscoveryFragment extends Fragment
        implements OnRefreshListener2<ListView>, OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discovery, container, false);
        ButterKnife.inject(this, view);
        back.setVisibility(View.GONE);
        rightImage.setVisibility(View.VISIBLE);
        rightImage.setImageResource(R.drawable.header_icon_search);
        rightImage.setOnClickListener(this);
        title.setText(R.string.discover);
        adapter = new DiscoveryAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), false,
                true);
        list.setOnScrollListener(listener);
        return view;
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getItems(1);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getItems(currentPage + 1);
    }

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        NetworkHelper.getInstance().getRequestQueue().cancelAll(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_image:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
        }
    }

    private List<DiscoveryItem> items = new ArrayList<>();

    private DiscoveryAdapter adapter;

    private class DiscoveryAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public DiscoveryItem getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DiscoveryViewHolder holder;
            View view = convertView;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.discovery_list_item, parent, false);
                holder = new DiscoveryViewHolder(view, getActivity(),
                        DiscoveryViewHolder.TYPE_DISCOVERY);
                view.setTag(holder);
            }
            holder = (DiscoveryViewHolder) view.getTag();
            DiscoveryItem item = getItem(position);
            holder.bindDiscoveryItem(item);
            holder.setAdapter(this);
            return view;
        }
    }

    private int currentPage = 0;

    private void getItems(final int page) {
        String url = NetworkConstants.DISCOVERY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("act", "lists");
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Method.POST,
                DiscoveryListResponse.class, true, params, new Listener<DiscoveryListResponse>() {
            @Override
            public void onResponse(DiscoveryListResponse response) {
                if (response.isSuccess()) {
                    if (page == 1) {
                        items.clear();
                    }
                    if (list != null) {
                        if (response.page == response.max_page) {
                            list.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        } else {
                            list.setMode(PullToRefreshBase.Mode.BOTH);
                        }
                    }
                    Collections.addAll(items, response.data);
                    adapter.notifyDataSetChanged();
                    currentPage = response.page;
                } else {
                    Utils.showToast(response.msg);
                }
                refreshComplete();
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Utils.showToast(R.string.generic_failure);
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }
}
